<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas Round Rect</title>
    <style>
        canvas {
            border: 1px solid gray;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <script>
        window.onload = function () {
            const canvas = document.getElementById('canvas');
            const ctx = canvas.getContext('2d');

            // 封装绘制圆角矩形的函数，支持填充和描边
            function drawRoundRect(x, y, width, height, radius, fillColor, strokeColor, strokeWidth) {
                ctx.beginPath();
                ctx.moveTo(x + radius, y);
                ctx.arcTo(x + width, y, x + width, y + radius, radius);
                ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius);
                ctx.arcTo(x, y + height, x, y + height - radius, radius);
                ctx.arcTo(x, y, x + radius, y, radius);
                ctx.closePath();

                // 如果传入了填充颜色，进行填充操作
                if (fillColor) {
                    ctx.fillStyle = fillColor;
                    ctx.fill();
                }

                // 如果传入了描边颜色和描边宽度，进行描边操作
                if (strokeColor && strokeWidth) {
                    ctx.strokeStyle = strokeColor;
                    ctx.lineWidth = strokeWidth;
                    ctx.stroke();
                }
            }

            // 使用示例
            const rectX = 50;
            const rectY = 50;
            const rectWidth = 300;
            const rectHeight = 300;
            const borderRadius = 20;
            const fill = '#f00';
            const stroke = 'blue';
            const strokeWidth = 5;

            drawRoundRect(rectX, rectY, rectWidth, rectHeight, borderRadius, fill, stroke, strokeWidth);
        }
    </script>
</body>

</html>